from os import error
from flask import Blueprint,render_template, request,session,redirect
from config import conn,cur,mutex ,r as redis
import datetime

VitalSigns = Blueprint('VitalSigns',__name__)
 
@VitalSigns.route('/',methods=["GET", "POST"])
def index():
    id = session.get('id') 
    name = session.get('name')

    sqlstr='select TOP 10 * from vital_signs  where person_id= \'' + str(id)+'\''
    print(sqlstr)
    cur.execute(sqlstr)
    result = cur.fetchall()
    
    return render_template('/vitalSigns/index.html',id =id,name=name,data=result )


@VitalSigns.route('/updatePage',methods=["GET", "POST"])
def updatePage():
    id = session.get('id') 
    name = session.get('name')
    return render_template('/vitalSigns/update.html',id =id,name=name )

@VitalSigns.route('/updateSigns',methods=["GET", "POST"])
def updateSigns():
    if request.method == "POST":
        sbp = request.form.get("sbp")
        dbp = request.form.get("dbp")
        glucose = request.form.get("glucose")
        cholesterol = request.form.get("cholesterol")
        SaO2 = request.form.get("SaO2")
    id = session.get('id') 
    try:

        datestr = datetime.datetime.now().strftime('%Y-%m-%d')
        sqlstr= 'delete from vital_signs where date = \'' + datestr + '\' and person_id= \''+str(id)+'\''
        print(sqlstr)
        mutex.acquire()
        cur.execute(sqlstr)
        conn.commit()
        mutex.release()

        sqlstr='insert into vital_signs (person_id,sbp,dbp,glucose,cholesterol,sao2) VALUES (\''+str(id)+'\',\''+sbp+'\',\''+dbp+'\',\''+glucose+'\',\''+cholesterol+'\',\''+SaO2+'\' )'
        print(sqlstr)
        mutex.acquire()
        cur.execute(sqlstr)
        conn.commit()
        mutex.release()
        
        return  {'message':"success!"}
    except error:
        return  {'message':error}

@VitalSigns.route('/logout',methods=["GET", "POST"])
def logout():
    session.clear()
    return {
        'message':"success!"
    }


@VitalSigns.before_request
def before():
    if session.get('id') is None or session.get('role') != 'patient':
        return redirect('/Login/',code=301)
    else:
            pass